<template>
  <a-spin :spinning="loading">
    <a-tabs v-model:activeKey="tabsActiveKey">
      <a-tab-pane key="1" tab="详细信息">
        <JFormContainer :disabled="disabled">
          <template #detail>
            <a-form v-bind="formItemLayout" name="EcArchiveInfoForm" ref="formRef">
              <a-row>
                <a-col :span="24">
                  <a-card title="会员账号信息">
                    <a-row>
                      <a-col :span="8">
                        <a-form-item label="头像" v-bind="validateInfos.avatar" id="EcArchiveInfoForm-avatar" name="avatar">
                          <j-image-upload :fileMax="0" v-model:value="formData.avatar"></j-image-upload>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="登录账号" v-bind="validateInfos.account" id="EcArchiveInfoForm-account" name="account">
                          <a-input v-model:value="formData.account" placeholder="请输入登录账号" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="护理员" v-bind="validateInfos.caregiver" id="EcArchiveInfoForm-caregiver" name="caregiver">
                          <j-select-user v-model:value="formData.caregiver" allow-clear />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="专家姓名" v-bind="validateInfos.expertName" id="EcArchiveInfoForm-expertName" name="expertName">
                          <a-input v-model:value="formData.expertName" placeholder="请输入专家姓名" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label=" 会员类型"
                          v-bind="validateInfos.membershipType"
                          id="EcArchiveInfoForm-membershipType"
                          name="membershipType"
                        >
                          <j-dict-select-tag
                            v-model:value="formData.membershipType"
                            dictCode="membership_type"
                            placeholder="请选择 会员类型"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="会员状态" v-bind="validateInfos.memberStatus" id="EcArchiveInfoForm-memberStatus" name="memberStatus">
                          <j-dict-select-tag
                            v-model:value="formData.memberStatus"
                            dictCode="member_status"
                            placeholder="请选择会员状态"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </a-card>
                </a-col>

                <a-col :span="24" style="margin-top: 10px">
                  <a-card title="会员基本信息">
                    <a-row>
                      <a-col :span="8">
                        <a-form-item label="会员姓名" v-bind="validateInfos.memberName" id="EcArchiveInfoForm-memberName" name="memberName">
                          <a-input v-model:value="formData.memberName" placeholder="请输入会员姓名" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="会员昵称"
                          v-bind="validateInfos.memberNickname"
                          id="EcArchiveInfoForm-memberNickname"
                          name="memberNickname"
                        >
                          <a-input v-model:value="formData.memberNickname" placeholder="请输入会员昵称" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="身份证号" v-bind="validateInfos.idNumber" id="EcArchiveInfoForm-idNumber" name="idNumber">
                          <a-input v-model:value="formData.idNumber" placeholder="请输入身份证号" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="手机号码" v-bind="validateInfos.phone" id="EcArchiveInfoForm-phone" name="phone">
                          <a-input v-model:value="formData.phone" placeholder="请输入手机号码" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="会员性别" v-bind="validateInfos.memberGender" id="EcArchiveInfoForm-memberGender" name="memberGender">
                          <j-dict-select-tag v-model:value="formData.memberGender" dictCode="sex" placeholder="请选择会员性别" allow-clear />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="电子邮箱" v-bind="validateInfos.email" id="EcArchiveInfoForm-email" name="email">
                          <a-input v-model:value="formData.email" placeholder="请输入电子邮箱" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="省市区" v-bind="validateInfos.region" id="EcArchiveInfoForm-region" name="region">
                          <j-area-linkage v-model:value="formData.region" placeholder="请输入省市区" saveCode="region" allow-clear />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="详细地址" v-bind="validateInfos.address" id="EcArchiveInfoForm-address" name="address">
                          <a-input v-model:value="formData.address" placeholder="请输入详细地址" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="身份标签" v-bind="validateInfos.identityLabel" id="EcArchiveInfoForm-identityLabel" name="identityLabel">
                          <j-select-multiple
                            type="list_multi"
                            v-model:value="formData.identityLabel"
                            dictCode="identity_label"
                            placeholder="请选择身份标签"
                            :triggerChange="false"
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="备注" v-bind="validateInfos.remarks" id="EcArchiveInfoForm-remarks" name="remarks">
                          <a-input v-model:value="formData.remarks" placeholder="请输入备注" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </a-card>
                </a-col>
                <a-col :span="24" style="margin-top: 10px">
                  <a-card title="会员详细信息">
                    <a-row>
                      <a-col :span="8">
                        <a-form-item label="民族" v-bind="validateInfos.nation" id="EcArchiveInfoForm-nation" name="nation">
                          <a-input v-model:value="formData.nation" placeholder="请输入民族" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label=" 籍贯" v-bind="validateInfos.placeOfOrigin" id="EcArchiveInfoForm-placeOfOrigin" name="placeOfOrigin">
                          <a-input v-model:value="formData.placeOfOrigin" placeholder="请输入 籍贯" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="政治面貌"
                          v-bind="validateInfos.politicalStatus"
                          id="EcArchiveInfoForm-politicalStatus"
                          name="politicalStatus"
                        >
                          <j-dict-select-tag
                            v-model:value="formData.politicalStatus"
                            dictCode="political_status"
                            placeholder="请选择政治面貌"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="文化程度"
                          v-bind="validateInfos.educationalLevel"
                          id="EcArchiveInfoForm-educationalLevel"
                          name="educationalLevel"
                        >
                          <j-dict-select-tag
                            v-model:value="formData.educationalLevel"
                            dictCode="educational_level"
                            placeholder="请选择文化程度"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="人员类别"
                          v-bind="validateInfos.personnelCategory"
                          id="EcArchiveInfoForm-personnelCategory"
                          name="personnelCategory"
                        >
                          <j-dict-select-tag
                            v-model:value="formData.personnelCategory"
                            dictCode="personnel_category"
                            placeholder="请选择人员类别"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="婚姻状况" v-bind="validateInfos.maritalStatus" id="EcArchiveInfoForm-maritalStatus" name="maritalStatus">
                          <j-dict-select-tag
                            v-model:value="formData.maritalStatus"
                            dictCode="marital_status"
                            placeholder="请选择婚姻状况"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="居住状况"
                          v-bind="validateInfos.residentialStatus"
                          id="EcArchiveInfoForm-residentialStatus"
                          name="residentialStatus"
                        >
                          <j-dict-select-tag
                            v-model:value="formData.residentialStatus"
                            dictCode="residential_status"
                            placeholder="请选择居住状况"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="经济来源"
                          v-bind="validateInfos.sourceOfIncome"
                          id="EcArchiveInfoForm-sourceOfIncome"
                          name="sourceOfIncome"
                        >
                          <j-checkbox
                            type="checkbox"
                            v-model:value="formData.sourceOfIncome"
                            dictCode="source_of_income"
                            placeholder="请选择经济来源"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="原单位" v-bind="validateInfos.oldUnit" id="EcArchiveInfoForm-oldUnit" name="oldUnit">
                          <a-input v-model:value="formData.oldUnit" placeholder="请输入原单位" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label=" 职称"
                          v-bind="validateInfos.professionalTitle"
                          id="EcArchiveInfoForm-professionalTitle"
                          name="professionalTitle"
                        >
                          <a-input v-model:value="formData.professionalTitle" placeholder="请输入 职称" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="月收入" v-bind="validateInfos.monthlyIncome" id="EcArchiveInfoForm-monthlyIncome" name="monthlyIncome">
                          <a-input v-model:value="formData.monthlyIncome" placeholder="请输入月收入" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label=" 宗教信仰"
                          v-bind="validateInfos.religiousBelief"
                          id="EcArchiveInfoForm-religiousBelief"
                          name="religiousBelief"
                        >
                          <j-dict-select-tag v-model:value="formData.religiousBelief" dictCode="" placeholder="请选择 宗教信仰" allow-clear />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="户籍所在地"
                          v-bind="validateInfos.registeredResidence"
                          id="EcArchiveInfoForm-registeredResidence"
                          name="registeredResidence"
                        >
                          <j-area-linkage v-model:value="formData.registeredResidence" placeholder="请输入户籍所在地" saveCode="region" allow-clear />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="户籍类型" v-bind="validateInfos.householdType" id="EcArchiveInfoForm-householdType" name="householdType">
                          <j-dict-select-tag
                            v-model:value="formData.householdType"
                            dictCode="household_type"
                            placeholder="请选择户籍类型"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="户籍详细地址"
                          v-bind="validateInfos.householdAddress"
                          id="EcArchiveInfoForm-householdAddress"
                          name="householdAddress"
                        >
                          <a-input v-model:value="formData.householdAddress" placeholder="请输入户籍详细地址" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="居住详细地址"
                          v-bind="validateInfos.residentialDetailedAddress"
                          id="EcArchiveInfoForm-residentialDetailedAddress"
                          name="residentialDetailedAddress"
                        >
                          <a-input v-model:value="formData.residentialDetailedAddress" placeholder="请输入居住详细地址" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </a-card>
                </a-col>
                <a-col :span="24" style="margin-top: 10px">
                  <a-card title="健康医疗信息">
                    <a-row>
                      <a-col :span="8">
                        <a-form-item
                          label="社保号"
                          v-bind="validateInfos.socialSecurityNumber"
                          id="EcArchiveInfoForm-socialSecurityNumber"
                          name="socialSecurityNumber"
                        >
                          <a-input v-model:value="formData.socialSecurityNumber" placeholder="请输入社保号" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="医疗保障"
                          v-bind="validateInfos.medicalSecurity"
                          id="EcArchiveInfoForm-medicalSecurity"
                          name="medicalSecurity"
                        >
                          <a-input v-model:value="formData.medicalSecurity" placeholder="请输入医疗保障" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="血型" v-bind="validateInfos.bloodType" id="EcArchiveInfoForm-bloodType" name="bloodType">
                          <j-dict-select-tag v-model:value="formData.bloodType" dictCode="blood_type" placeholder="请选择血型" allow-clear />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="慢性病" v-bind="validateInfos.chronicDisease" id="EcArchiveInfoForm-chronicDisease" name="chronicDisease">
                          <a-input v-model:value="formData.chronicDisease" placeholder="请输入慢性病" allow-clear></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item
                          label="失能情况"
                          v-bind="validateInfos.disabilitySituation"
                          id="EcArchiveInfoForm-disabilitySituation"
                          name="disabilitySituation"
                        >
                          <j-dict-select-tag
                            v-model:value="formData.disabilitySituation"
                            dictCode="disability_situation"
                            placeholder="请选择失能情况"
                            allow-clear
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="服务类型" v-bind="validateInfos.serviceType" id="EcArchiveInfoForm-serviceType" name="serviceType">
                          <j-dict-select-tag v-model:value="formData.serviceType" dictCode="service_type" placeholder="请选择服务类型" allow-clear />
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </a-card>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </JFormContainer>
      </a-tab-pane>
      <a-tab-pane key="2" tab="紧急联系人" force-render>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="ecEmergencyContactTableRef"
          :loading="ecEmergencyContactTable.loading"
          :columns="ecEmergencyContactTable.columns"
          :dataSource="ecEmergencyContactTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryEcEmergencyContactListByMainId, queryDataById, saveOrUpdate } from '../EcArchiveInfo.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { ecEmergencyContactColumns } from '../EcArchiveInfo.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
  import JSelectUser from '/@/components/Form/src/jeecg/components/JSelectUser.vue';
  import JAreaLinkage from '/@/components/Form/src/jeecg/components/JAreaLinkage.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JCheckbox from '/@/components/Form/src/jeecg/components/JCheckbox.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { Form } from 'ant-design-vue';
  import { getDateByPicker } from '/@/utils';
  import dayjs from 'dayjs';
  const useForm = Form.useForm;
  const activeKey = ref('1');
  export default defineComponent({
    name: 'EcArchiveInfoForm',
    components: {
      JDictSelectTag,
      JSelectMultiple,
      JSelectUser,
      JAreaLinkage,
      JImageUpload,
      JCheckbox,
      JVxeTable,
      JFormContainer,
    },
    props: {
      formDisabled: {
        type: Boolean,
        default: false,
      },
      formData: { type: Object, default: () => {} },
      formBpm: { type: Boolean, default: true },
    },
    emits: ['success'],
    setup(props, { emit }) {
      const loading = ref(false);
      const formRef = ref();
      const ecEmergencyContactTableRef = ref();
      const ecEmergencyContactTable = reactive<Record<string, any>>({
        loading: false,
        columns: ecEmergencyContactColumns,
        dataSource: [],
      });
      const activeKey = ref('ecEmergencyContact');
      const formData = reactive<Record<string, any>>({
        id: '',
        avatar: '',
        account: '',
        caregiver: '',
        expertName: '',
        membershipType: '',
        memberStatus: '',
        memberName: '',
        memberNickname: '',
        idNumber: '',
        phone: '',
        memberGender: '',
        email: '',
        region: '',
        address: '',
        identityLabel: '',
        remarks: '',
        nation: '',
        placeOfOrigin: '',
        politicalStatus: '',
        educationalLevel: '',
        personnelCategory: '',
        maritalStatus: '',
        residentialStatus: '',
        sourceOfIncome: '',
        oldUnit: '',
        professionalTitle: '',
        monthlyIncome: '',
        religiousBelief: '',
        registeredResidence: '',
        householdType: '',
        householdAddress: '',
        residentialDetailedAddress: '',
        socialSecurityNumber: '',
        medicalSecurity: '',
        bloodType: '',
        chronicDisease: '',
        disabilitySituation: '5',
        serviceType: '',
      });

      //表单验证
      const validatorRules = reactive({});
      const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
      //日期个性化选择
      const fieldPickers = reactive({});
      const dbData = {};
      const formItemLayout = {
        labelCol: { xs: { span: 24 }, sm: { span: 5 } },
        wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
      };

      // 表单禁用
      const disabled = computed(() => {
        if (props.formBpm === true) {
          if (props.formData.disabled === false) {
            return false;
          } else {
            return true;
          }
        }
        return props.formDisabled;
      });

      function add() {
        resetFields();
        ecEmergencyContactTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const ecEmergencyContactDataList = await queryEcEmergencyContactListByMainId(row['id']);
        ecEmergencyContactTable.dataSource = [...ecEmergencyContactDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if (row.hasOwnProperty(key)) {
            tmpData[key] = row[key];
          }
        });
        //赋值
        Object.assign(formData, tmpData);
      }

      const { getSubFormAndTableData, transformData } = useValidateAntFormAndTable(activeKey, {
        ecEmergencyContact: ecEmergencyContactTableRef,
      });

      async function getFormData() {
        try {
          // 触发表单验证
          await validate();
        } catch ({ errorFields }) {
          if (errorFields) {
            const firstField = errorFields[0];
            if (firstField) {
              formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
            }
          }
          return Promise.reject(errorFields);
        }
        return transformData(toRaw(formData));
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        // 预处理日期数据
        changeDateValue(mainData, subData);
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values);
        const isUpdate = values.id ? true : false;
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }

      function setFieldsValue(values) {
        if (values) {
          Object.keys(values).map((k) => {
            formData[k] = values[k];
          });
        }
      }

      /**
       * 处理日期值
       * @param formData 表单数据
       */
      const changeDateValue = (mainData, subData) => {
        for (let key in mainData) {
          // 更新个性化日期选择器的值
          mainData[key] = getDateByPicker(mainData[key], fieldPickers[key]);
        }
        if (subData.ecEmergencyContactList && subData.ecEmergencyContactList.length > 0) {
          ecEmergencyContactColumns.forEach((subFormField) => {
            if (subFormField && subFormField.picker && subFormField.key) {
              let subPicker = subFormField.picker;
              const subFieldName = subFormField.key;
              subData.ecEmergencyContactList.forEach((subFormData) => {
                if (subPicker === 'year') {
                  subFormData[subFieldName] = dayjs(subFormData[subFieldName]).set('month', 0).set('date', 1).format('YYYY-MM-DD');
                } else if (subPicker === 'month') {
                  subFormData[subFieldName] = dayjs(subFormData[subFieldName]).set('date', 1).format('YYYY-MM-DD');
                } else if (subPicker === 'week') {
                  subFormData[subFieldName] = dayjs(subFormData[subFieldName]).startOf('week').format('YYYY-MM-DD');
                }
              });
            }
          });
        }
      };

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }

      return {
        ecEmergencyContactTableRef,
        ecEmergencyContactTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
      };
    },
  });
</script>
<style lang="less" scoped>
  .ant-tabs-tabpane.sub-one-form {
    max-height: 340px;
    overflow: auto;
  }
</style>
